<?php

class UserController extends Controller
{
	/**
	 * @var CActiveRecord the currently loaded data model instance.
	 */
	private $_model;
	public $userStatus = array(1=>'active',0=>'register',-9=>'deleted',-1=>'blocked',-8=>'forced');
	public $userPrivs = array(1=>'SuperUser',0=>'Registered',-9=>'deleted',-1=>'blocked',-8=>'forced');
	public $activationUrl = '/user/activation/';
	public $newPwdUrl = '/user/resetpwd';	
	public $registrationEmail='ppe@audelion.ch';
	//public $layout='column2';
	public function actions()
	{
		return array(
			'captcha'=>array(
				'class'=>'MathCaptchaAction',
				'backColor'=>0xF8F8F8,
				'minLength' => 1,
				'maxLength' => 10,
			),
			// page action renders "static" pages stored under 'protected/views/site/pages'
			// They can be accessed via: index.php?r=site/page&view=FileName
			'page'=>array(
				'class'=>'CViewAction',
			),
		);
	}
	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return CMap::mergeArray(parent::filters(),array(
			'accessControl', // perform access control for CRUD operations
		));
	}
	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow',  // allow all users to perform 'index' and 'view' actions
				//'actions'=>array('*'), //'index','view', 'registration', 'changepassword', 'activation', 'getpassword'),
				'users'=>array('*'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}	

	/**
	 * Displays a particular model.
	 */
	public function actionView() {
	
	$facebook = new Facebook(array(
  'appId'  => '424168224273806',
  'secret' => 'a5acf3c1936efc02a39d03e5e91b9fbf',
));
		$user=array();
		$model = User::model()->findbyPk(Yii::app()->user->id);
		if(strlen($model->fb) >1 )
		$user=$facebook->api('/'.$model->fb); 
		$this->render('view',array(
			'model'=>$model,
			'fb'=>$user,
		));
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex() {
		$user = User::model()->findbyPk(Yii::app()->user->id);
		if(!$user->isAdmin()){

			$this->render('view',array(
				'model'=>$user,
			));
		} // $user->isAdmin()
		else
		{
			$dataProvider=new CActiveDataProvider('User', array(
		//'criteria'=>array(
        //					'condition'=>'status>0',
    	//					),
    						
		 	'pagination'=>array(
        			'pageSize'=>6,
    				),
			));
		$dataProvider->getData(); //->getData();
		$this->render('index',array(
			'dataProvider'=>$dataProvider,
		));
		}
	}
        // Send the Email to the given user object. $user->email needs to be set.
    public function actionActivation($email,$key) {
        	    //$model=new User;
        	    	$model=User::model()->find('email=:email',array(':email' => $email));
        	    	if ($model->status == 1) {
        	    	    //Yii::app()->user->setFlash('error', "Data2 failed!");
						Yii::app()->user->setFlash('notice', "account is already activated !");
        	    		$this->render('reg_failure',array('message'=> 'account is already activated !'));
        	    		Yii::app()->end();
        	    	}
        	    	if ($model->activkey === $key) {
        	    		$model->activkey = '';
        	    		$model->status = 1;
        	    		$model->save();
        	    		$this->render('reg_success',array('model'=>$model));
        	    	}
        	    	else $this->render('reg_failure',array('message'=>'internal error'));
        	    	

        }
/**
 * reset the pwd
 */
public function actionResetpwd($user,$link)
{
    $model=User::model()->findbyPk($user);
    if($model->password == $link){
    	$userIdentity=new UserIdentity($model->username,'12qw');
    	if(!$userIdentity->authenticate()) echo 'wrong';
    	$this->redirect('/index.php/user/changepassword/id/'.$user);
	}
    $this->redirect('/');
}
public function actionActivationx($user, $key=0)
{
    $model=$user = User::model()->findbyPk($user);
    if($key == $model->activkey ) {
    	$model->activkey = '';
    	$model->status = 1;
    	$model->save();
    	$this->render('reg_success',array('model'=>$model)); 
    }
    $this->render('reg_failure',array('model'=>$model));
}
public function actionRegistration()
{
    $model=new User;
    $this->performAjaxValidation($model);
    if(isset($_POST['User']))
    {
    $model->validate();
        $model->attributes=$_POST['User'];
        if($model->save()){
        	$this->sendRegistrationEmail($model);
            $this->redirect(array('/'));
        }    
    }
    $this->render('create',array('model'=>$model));
}

        // Send the Email to the given user object. $user->email needs to be set.
        public function sendNewPwdEmail($user) {
                if (!isset($user->email)) {
                        throw new CException('Email is not set when trying to send new Pwd Email');
                }
                $activation_url = $this->newPwdUrl;

                // get the text to sent from the yumtextsettings table
                //$content = YumTextSettings::model()->find('language = :lang', array(
                //                        'lang' => Yii::app()->language));
                $sent = null;
                // Always set content-type when sending HTML email
	$headers = "MIME-Version: 1.0" . "\r\n";
	$headers .= "Content-Type: text/html; charset=utf-8" . "\r\n";
	$headers .= "From: " . $this->registrationEmail . "\r\n";
	$headers .= "X-Sender-IP: $_SERVER[SERVER_ADDR]\r\n";
	$headers .= 'Date: ' . date('n/d/Y g:i A') . "\r\n";
	$multipart .= '<h1>Passwort Reset</h1>';
	$multipart .= '<table><tr><td with="20px"></td><td>TestServices.ch</td></tr>';
	$multipart .= '<tr><td></td></td>Dies ist ein automatisiertes Mail; bitte nicht antworten.</td></tr>'. "\r\n";
	$multipart .=		'<br />'."\r\n".
	'dein neues Passwort kann du hier '.
							'<p><a href="http://www.testservices.ch/index.php'.$this->newPwdUrl.'/user/';
	$multipart .= $user->id.'/link/'.$user->password.'">http://www.testservices.ch'.$this->newPwdUrl.'</a>'." setzen<p>".
							'_________________________________________________________________________<br />';
	$multipart .= '<hl><div><p>'.
                        		'wenn du keine Anfrage gestellt hast, kann du diese Adresse löschen lassen'.
                        		'</p></div>';
            mail ($user->email, 'AW: Deine Anfrage zum Passwort Reset', $multipart, $headers);
        	return $sent;
        }

        // Send the Email to the given user object. $user->email needs to be set.
        public function sendRegistrationEmail($user) {
                if (!isset($user->email)) {
                        throw new CException('Email is not set when trying to send Registration Email');
                }
                $activation_url = $this->activationUrl;

                // get the text to sent from the yumtextsettings table
                //$content = YumTextSettings::model()->find('language = :lang', array(
                //                        'lang' => Yii::app()->language));
                $sent = null;
	$headers = "MIME-Version: 1.0" . "\r\n";
	$headers .= "Content-Type: text/html; charset=utf-8" . "\r\n";
	$headers .= "From: " . $this->registrationEmail . "\r\n";
	$headers .= "X-Sender-IP: $_SERVER[SERVER_ADDR]\r\n";
	$headers .= 'Date: ' . date('n/d/Y g:i A') . "\r\n";                        
	
	$multipart .= '<h1>Benutzer Registrierung</h1>';
	$multipart .= '<table><tr><td with="20px"></td><td>TestServices.ch</td></tr>';
	$multipart .= '<tr><td></td></td>Dies ist ein automatisiertes Mail; bitte nicht antworten.</td></tr>'. "\r\n";
	$multipart .=		'<br />'."\r\n".
							'du kannst deinen User Account mit diesem Link '.
							'<p><a href="http://www.testservices.ch/index.php'.$this->activationUrl.'email/'.$user->email.'/key/'.$user->activkey;
	$multipart .= '">http://www.testservices.ch/index.php'.$this->activationUrl.'email/'.$user->email.'/key/'.$user->activkey.'</a>'." aktivieren<p>".
							'_________________________________________________________________________<br />';
	$multipart .= '<hl><div><p>'.
                        		'wenn du keine Anfrage gestellt hast, kann du diese Adresse löschen lassen'.
                        		'</p></div>';

                        mail ($user->email, 'Deine Registrierung für TestServices', $multipart, $headers);


                return $sent;
        }
protected function performAjaxValidation($model)
{
    if(isset($_POST['ajax']) && $_POST['ajax']==='user-form')
    {
        echo CActiveForm::validate($model);
        Yii::app()->end();
    }
}
	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 */
	public function loadModel()
	{
		if($this->_model===null)
		{
			if(isset($_GET['id']))
				$this->_model=User::model()->findbyPk($_GET['id']);
			if($this->_model===null)
				throw new CHttpException(404,'The requested page does not exist.');
		}
		return $this->_model;
	}
	/**
	 * request NEW password
	 */
	public function actionGetpassword() {
		$model = new UserNewPassword;
    	if(isset($_POST['UserNewPassword']))	{
    	    $model->attributes=$_POST['UserNewPassword'];
    		$user = User::model()->find("email='".$model->email."'");
    		if($user===null) {
    			Yii::app()->user->setFlash('newpassword','Die eMail - <b>'.$model->email.'</b> - ist nicht registriert');
    			$this->refresh();
    		}
    			
    		else {
				//$user->password = 
					$this->sendNewPwdEmail($user);
				Yii::app()->user->setFlash('newpassword','Das neue Passwort wurde an <b>'.$model->email.'</b> gesendet');
				$this->refresh();
				}   
			}
			$this->render('getpassword',array('model'=>$model));

	}
	/**
	 * Change password
	 */
	public function actionChangepassword($id=-1) {
			$model = new UserChangePassword;
			//echo 'user: '.Yii::app()->user->id;
			if($id<0) $id = Yii::app()->user->id;
			//if (Yii::app()->user->id) {
					
					// ajax validator
					if(isset($_POST['ajax']) && $_POST['ajax']==='changepassword-form')
					{
							echo UActiveForm::validate($model);
							Yii::app()->end();
					}

					if(isset($_POST['UserChangePassword'])) {
									$model->attributes=$_POST['UserChangePassword'];
									if($model->validate()) {
											$user = User::model()->findbyPk($id);
											$user->newPassword($model->password);
											Yii::app()->user->setFlash('profileMessage',"New password is saved.");
											$this->redirect(array("/"));
									}
					}

					$this->render('changepassword',array('model'=>$model));
		//}
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the primary key value. Defaults to null, meaning using the 'id' GET variable
	 */
	public function loadUser($id=null)
	{
		if($this->_model===null)
		{
			if($id!==null || isset($_GET['id']))
				$this->_model=User::model()->findbyPk($id!==null ? $id : $_GET['id']);
			if($this->_model===null)
				throw new CHttpException(404,'The requested page does not exist.');
		}
		return $this->_model;
	}
}